<template>
	<view class="userLogin">
		<view class="login_container">
			<view class="inputItem">
				<view class="inputItem_label"><text>手机号</text></view>
				<view class="inputItem_input">
					<tui-input :labelWidth="82" radius="68" labelSize="32" labelColor="#FFFFFF" color="#FFFFFF"
						size="32" :backgroundColor="'rgba(255,255,255,0.5);'" label="+86" placeholder="请输入手机号"
						v-model="form.phonenumber"></tui-input>
				</view>
			</view>
			<view class="inputItem">
				<view class="inputItem_label"><text>验证码</text></view>
				<view class="inputItem_input">
					<tui-input padding="32rpx 42rpx" :labelWidth="82" radius="68" color="#FFFFFF" size="32"
						:backgroundColor="'rgba(255,255,255,0.5);'" placeholder="请输入验证码" v-model="form.code">
						<template v-slot:right>
							<view class="sendCode" @tap="handleGetCode"><text>{{ smsText }}</text></view>
						</template>
					</tui-input>
				</view>
			</view>
			<view class="desc">
				<view @tap="checked = !checked">
					<tutor-checkbox :checked="checked"></tutor-checkbox>
				</view>
				<view class="agreement">我已阅读并同意<text class="a" @tap="userAgreement">《用户服务协议》</text>和<text class="a"
						@tap="privacypolicy">《隐私政策》</text></view>
			</view>
			<tui-form-button @click="tapLogin" margin="52rpx 0 0 0" radius="58rpx" size="32" color="#fff" width="602rpx"
				height="108rpx" background="#2FD7D3">登录</tui-form-button>

			<!-- h5微信登录 -->
			<!-- #ifdef H5 -->
			<view style="display: flex;justify-content: center;">
				<tui-form-button plain @click="tapAutoLogin" margin="52rpx 0 0 0" radius="58rpx" size="32"
					color="#2FD7D3" width="602rpx" height="88rpx" background="#2FD7D3">微信快捷登录</tui-form-button>
			</view>
			<!-- #endif -->
			<!-- end -->
		</view>
	</view>
</template>

<script>
	import {
		h5Login,
		getCode
	} from "@/http/api/user/user.js"
	import {
		h5AutoLogin
	} from "@/http/api/user/user.js"
	import Cache from "@/utils/cache";
	export default {
		data() {
			return {
				checked: false,
				smsCode: 60, //发送秒
				smsText: '发送验证码',
				timmer: null,
				code: '',
				userInfo: {},
				hasRequestedAuth: false, // 标志位
				form: {
					phonenumber: '', //手机号
					code: '' //验证码
				},
			}
		},
		computed:{
			isWeChatBrowser() {
			    const ua = window.navigator.userAgent.toLowerCase();
			    return ua.includes('micromessenger');
			},
		},
		onShow() {
			// #ifdef H5
			// 1. 手动解析 URL 中的 code（兼容 Hash 模式）
			const urlParams = new URLSearchParams(window.location.search);
			const code = urlParams.get('code');

			if (code) {
				this.code = code;
				// 清除 URL 中的 code 参数
				const newUrl = window.location.pathname + window.location.hash;
				window.history.replaceState({}, document.title, newUrl);
			} else if (!this.hasRequestedAuth && this.isWeChatBrowser) {
				this.hasRequestedAuth = true;
				localStorage.setItem('hasRequestedAuth', 'true'); // 持久化状态
				this.getWeixinAuthUrl();
			}
			// #endif
		},
		methods: {
			getWeixinAuthUrl() {
				// #ifdef H5
				// 生成无参数的 redirect_uri（避免微信重复附加 code）
				const cleanUrl = window.location.origin + '/#/pages/mine/modules/userLogin/userLogin';
				console.log(window.location.origin, window.location.pathname, '地址')
				const redirect_uri = encodeURIComponent(cleanUrl);

				// 添加随机 state 防篡改
				const state = Math.random().toString(36).substr(2);
				localStorage.setItem('wx_auth_state', state);

				const authUrl =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8432b1d63afc4005&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
				window.location.href = authUrl;
				// #endif
			},
			//用户协议
			userAgreement() {
				uni.navigateTo({
					url: '/pages/mine/modules/richText/richText?type=' + 1
				})
			},
			//隐私协议
			privacypolicy() {
				uni.navigateTo({
					url: '/pages/mine/modules/richText/richText?type=' + 2
				})
			},
			async tapAutoLogin() {
				let that = this
				uni.showLoading({
					title: '登录中'
				});
				h5AutoLogin({
					wxCode: this.code,
				}).then(res => {
					if (res.code === 200) {
						Cache.set('access_token', res.data.access_token);
						this.$store.dispatch('getUserInfo');
						this.$store.dispatch('getCategorys');
						uni.reLaunch({
							url:'/pages/tutor/tutor'
						})
						// uni.switchTab({
						// 	url: '/pages/tutor/tutor'
						// })
					}
				}).finally(() => {
					uni.hideLoading();
				})

			},
			//获取验证码
			handleGetCode() {
				let self = this;
				if (self.isCountDown) return false;
				if (!self.checked) {
					self.$utils.toast('请同意用户协议和隐私协议');
					return false;
				}
				if (!self.form.phonenumber) {
					self.$utils.toast('请输入手机号');
					return false;
				} else if (!self.$regexp.phone.test(self.form.phonenumber)) {
					self.$utils.toast('请输入正确的手机号');
					return false;
				}
				getCode({
					phonenumber: self.form.phonenumber
				}).then(res => {
					if (res.code == 200) {
						self.countDown();
					} else {
						self.$utils.toast(res.message);
					}
				});
			},
			//启动倒计时
			countDown() {
				let self = this;
				self.isCountDown = true;
				self.timmer = setInterval(function() {
					self.smsCode--;
					if (self.smsCode <= 0) {
						self.isCountDown = false;
						self.smsCode = 60;
						clearInterval(self.timmer);
						self.smsText = '重新获取验证码';
						return false;
					}
					self.smsText = self.smsCode + '秒后重新获取';
				}, 1000);
			},
			tapLogin() {
				if (!this.form.code) {
					this.$utils.toast('请输入验证码');
					return false;
				}
				if (this.userInfo.errMsg == "getPhoneNumber:fail user deny") { //用户拒绝授权
					this.wxlogin()
					return;
				} else {
					let extendCode = Cache.get('extendCode')
					h5Login({
						phonenumber: this.form.phonenumber,
						smsCode: this.form.code,
						wxCode: this.code,
						distributionCode: extendCode
					}).then(res => {
						if (res.code == 200) {
							Cache.set('access_token', res.data.access_token);
							this.$store.dispatch('getUserInfo');
							this.$store.dispatch('getCategorys');
							uni.switchTab({
								url: '/pages/tutor/tutor'
							})
						} else {
							this.$utils.toast(res.msg)
						}
					})
				}
			}
		}

	}
</script>

<style lang="scss" scoped>
	.userLogin {
		width: 100vw;
		height: 100vh;
		background-image: $userLogin-bg-base64;
		background-size: cover;
		display: flex;
		justify-content: center;
		align-items: center;

		.login_container {
			height: auto;
			width: 600rpx;

			.inputItem {
				margin-bottom: 66rpx;

				.inputItem_label {
					font-weight: bold;
					font-size: 36rpx;
					color: #FFFFFF;
					line-height: 42rpx;
				}

				.inputItem_input {
					margin-top: 24rpx;

					::v-deep .input-placeholder {
						color: #fff !important;
					}
				}

				.sendCode {
					font-weight: 500;
					font-size: 32rpx;
					color: #FFE600;
					line-height: 38rpx;
					text-align: right;
				}
			}

			.desc {
				display: flex;
				align-items: center;
				margin-top: 94rpx;

				.agreement {
					margin-left: 10rpx;
					font-weight: 500;
					font-size: 24rpx;
					color: #FFFFFF;
					line-height: 28rpx;

					.a {
						color: #2FD7D3;
					}
				}
			}
		}
	}
</style>